package org.stragma.apply.util

import scala.collection.mutable.HashMap

import org.kiama.rewriting._
import org.kiama.rewriting.Rewriter.{fail,id,rulefs,Strategy,Term}

import org.stragma.apply.signatures.Apply._

/**
 *	Unlike Stratego Kiama has no support dynamic rules. This class
 *	is a rough approximation of the dynamic rule feature available
 *  in Stratego
 */
class DynamicRules {
	
	private val matchRules : HashMap[TExp, Strategy] = new HashMap[TExp, Strategy]()
	
	/**
	 *	Support for adding a new rule
	 */
	def + (matchExp : TExp, newRule : Strategy) : Strategy = {
		
		// If the match rule exists then just rewrite it, else
		// create the new rule
		if (matchRules.contains (matchExp)) {
			matchRules (matchExp) = newRule
		} else {
			matchRules += matchExp -> newRule
		}
		
		// After the state of the dynamic rule has been altered return it back
		// as a proper strategy
		getStrategies
	}
	
	/**
	 *	Support for removing a rule
	 */
	def - (matchExp : TExp) : Strategy = {
		// Check to see if the rule exists and if it does remove it and rebuild the dynamic rule
		if (matchRules.contains (matchExp)) {
			matchRules -= matchExp
		}
		
		getStrategies
	}
	
	/**
	 *	Rebuils a strategy using all the entries in the Hashmap
	 */
	def getStrategies : Strategy = {
		var newStrategy = fail
		
		matchRules foreach { 
			rule => newStrategy = newStrategy <+ rule 
		}
		
		// return the strategies
		newStrategy
	}
}